<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Attributes\SearchUsingFullText;
use Laravel\Scout\Searchable;

class Book extends Model
{
    use HasFactory;
    use Searchable;

//    protected $appends = ['unique_jd_books', 'unique_dd_books'];
    protected $casts = [
        'unique_jd_books' => 'array',
        'unique_dd_books' => 'array'
    ];

    public function getUniqueJdBooksAttribute(){
        return JDBook::query()->whereIn(
            'id', function ($query){
            $query->from('j_d_books')->where('isbn', '=', $this->isbn)->groupBy('jd_id')->selectRaw('max(id)');
        })->get();
    }

    public function getUniqueDdBooksAttribute(){
        return DDBook::query()->whereIn(
            'id', function ($query){
            $query->from('d_d_books')->where('isbn', '=', $this->isbn)->groupBy('dd_id')->selectRaw('max(id)');
        })->get();
    }

    public function jd_books()
    {
        return $this->hasMany(JDBook::class, 'isbn','isbn');
    }

    public function dd_books()
    {
        return $this->hasMany(DDBook::class, 'isbn','isbn');
    }

    #[SearchUsingFullText(['digest','name'])]
    public function toSearchableArray()
    {
        return [
            'name' => $this->name,
            'digest' => $this->digest,
            'publisher' => $this->publisher,
            'author' => $this->author,
            'translator' => $this->translator,
        ];
    }
}
